package com.shujia.scala

import java.util.Scanner

object Demo28Match {
  def main(args: Array[String]): Unit = {
    /**
     * 模式匹配
     * java中的模式匹配可以匹配基本数据类型，字符串，枚举
     * scala中的模式匹配可以匹配基本数据类型，字符串，枚举，样例类，匹配类型
     *
     */

    //1、匹配基本数据类型
    //val i: Int = new Scanner(System.in).nextInt()
    val i = 10

    i match {
      case 10 => println(s"i=10")
      case 100 => println(s"i=100")
      case 1000 => println(s"i=1000")
      case 10000 => println(s"i=10000")
      case _ => println("其它")
    }

    //2、匹配字符串
    val str = "java"
    str match {
      case "java" => println("s=java")
      case "hadoop" => println("s=hadoop")
      case "spark" => println("s=spark")
      case "hive" => println("s=hive")
      case _ => println("其它")
    }

    //3、匹配样例类
    case class User(id: String, name: String, age: Int)

    val user: User = User("001", "张三", 23)

    user match {
      case User("001", "张三", 23) => println(user)
      case User("002", "李四", 23) => println(user)
      case User("003", "王五", 23) => println(user)
      case User("004", "赵六", 23) => println(user)
      case _ => println("其它")
    }


    //4、匹配类型
    val obj: Any = 1.1

    obj match {
      case i: Int => println(s"obj是一个int类型，obj=${i}")
      case str: String => println(s"obj是一个String类型，obj=${str}")
      case user: User => println(s"obj是一个User类型，obj=${user}")
      case _ => println(s"obj是其它类型，obj=$obj")
    }

    /**
     * match可以有返回值
     *
     */

    //val j: Int = new Scanner(System.in).nextInt()
    val j = 100

    //使用if 实现
    var flag = ""
    if (j % 2 == 1) {
      flag = "奇数"
    } else {
      flag = "偶数"
    }

    //match可以有返回值
    val flag1: String = j % 2 match {
      case 1 => "奇数"
      case 0 => "偶数"
    }
    println(flag1)

    /**
     * 模式匹配应用
     *
     */
    val map: Map[String, Int] = Map("001" -> 23, "002" -> 24)

    /**
     * Option: 有两个取值
     * 有值：Some
     * 为空：None
     */
    val value: Option[Int] = map.get("008")

    val age: Int = value match {
      case Some(v) => v //如果key存在返回value
      case None => 0 //如果key不存在返回默认值
    }

    println(age)


    /**
     * 在以函数作为参数时使用模式匹配
     *
     */

    val list: List[(String, (String, Int))] = List(
      ("001", ("张三", 23)),
      ("002", ("李四", 24)),
      ("003", ("王五", 25)),
      ("004", ("赵六", 26))
    )

    //取出id和年龄
    val idAndAge: List[(String, Int)] = list.map((kv: (String, (String, Int))) => {
      val id: String = kv._1
      val name: String = kv._2._1
      val age: Int = kv._2._2
      (id, age)
    })

    //使用case
    val idAndAge1: List[(String, Int)] = list.map {
      //匹配集合中元素的类型
      //后面没有用到的字段可以使用下划线占位
      case (id: String, (_: String, age: Int)) =>
        (id, age)
    }
    idAndAge1.foreach(println)


  }

}
